package com.heima.listener;

import cn.hutool.json.JSONUtil;
import com.heima.dto.ItemDTO;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ItemAddListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 实时同步  新增
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.save.queue",durable = "true"),
            exchange = @Exchange(name = "item-exchange",type = ExchangeTypes.TOPIC),
            key = "#.save"
    ))
    public void listenerItemAdd(ItemDTO item) throws IOException {
            IndexRequest request = new IndexRequest("items").id(item.getId().toString());
            request.source(JSONUtil.toJsonStr(item), XContentType.JSON);
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
            log.info("item新增成功，{}",item);
    }

    /**
     * 实时同步  修改状态
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.update.queue",durable = "true"),
            exchange = @Exchange(name = "item-exchange",type = ExchangeTypes.TOPIC),
            key = "#.update"
    ))
    public void listenerItemStatusUpdate(ItemDTO item) throws IOException {
        // 创建request
        UpdateRequest request = new UpdateRequest("items", item.getId().toString());
        // 封装DSL语句
        request.doc(
                "status",item.getStatus()
        );
        // 执行操作
        restHighLevelClient.update(request,RequestOptions.DEFAULT);
        log.info("item修改状态成功，{}",item);
    }

    /**
     * 实时同步  删除
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.delete.queue",durable = "true"),
            exchange = @Exchange(name = "item-exchange",type = ExchangeTypes.TOPIC),
            key = "#.delete"
    ))
    public void listenerDeleteById(Long id) throws IOException {
        // 创建request
        DeleteRequest request = new DeleteRequest("items", id.toString());
        // 封装DSL语句
        // 执行操作
        restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        log.info("item删除成功，{}",request);
    }
}
